#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/9/2
# @Author  : YunZhen
# @File    : _load.py
# @Software: PyCharm
"""
版本缓存管理模块
"""
import os
import json
import time
from loguru import logger

# 版本缓存文件路径
VERSION_CACHE_FILE = os.getenv('VERSION_CACHE_FILE')
if not VERSION_CACHE_FILE:
    raise ValueError("环境变量 'VERSION_CACHE_FILE' 未设置")

# 缓存有效期（1天）
CACHE_EXPIRY = os.getenv('CACHE_EXPIRY', 86400)


async def get_cached_versions():
    """获取缓存的版本列表"""
    logger.debug(f"从缓存文件: {VERSION_CACHE_FILE}读取版本信息")
    if os.path.exists(VERSION_CACHE_FILE):
        # 检查缓存是否过期
        cache_age = time.time() - os.path.getmtime(VERSION_CACHE_FILE)
        if cache_age < int(CACHE_EXPIRY):
            try:
                # todo: 修改为异步读取，当前是同步读取
                with open(VERSION_CACHE_FILE, 'r') as f:
                    logger.debug("版本缓存读取成功")
                    return json.load(f)
            except Exception as err:
                logger.error(f"读取缓存时出错: \nfile:{VERSION_CACHE_FILE} \n{str(err)}")
        else:
            logger.warning("版本缓存已过期，需重新获取")
    logger.warning("版本缓存文件不存在: {}", VERSION_CACHE_FILE)
    return None


async def update_version_cache(versions):
    """更新版本缓存"""
    logger.info(f"更新版本缓存文件: {VERSION_CACHE_FILE}")
    with open(VERSION_CACHE_FILE, 'w') as stream:
        json.dump(versions, stream, indent=4)
    return True


def generate_markdown(releases):
    md = "# Python版本发布历史记录\n\n"

    for platform, versions in releases.items():
        md += f"## {platform}版本\n\n"

        for version in versions:
            md += f"### {version['version']}\n"
            md += f"- **发布日期**: {version['date']}\n"
            md += "- **下载链接**:\n"

            for download in version['downloads']:
                md += f"  - [{download['name']}]({download['url']})\n"

            md += "\n"

    # 保存到文件
    with open("python_releases.md", "w", encoding="utf-8") as f:
        f.write(md)
    return md




